let phone = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
const App = getApp()
import QRCode from '../../../utils/weapp-qrcode.js';
const W = wx.getSystemInfoSync().windowWidth;
const rate = 1000.0 / W;
 
// 300rpx 在6s上为 150px
const qrcode_w = 300 / rate;

Page({
  data: {
    qrcode_w: qrcode_w,
    showCode:false,
    taskTitle: "",
    option1: [{
        text: '扶助苦难群体',
        value: 0
      },
      {
        text: '发展农业生产',
        value: 1
      },
      {
        text: '促进邻里互助',
        value: 2
      },
      {
        text: '倡导文明风尚',
        value: 3
      },
      {
        text: '关怀儿童教育',
        value: 4
      },
      {
        text: '协调矛盾冲突',
        value: 5
      },
      {
        text: '保护生态环境',
        value: 6
      },
      {
        text: '其它',
        value: 7
      },
      {
        text: '请选择任务类型',
        value: 8
      },
    ],
    taskType: "请选择任务类型",
    value1: 8,
    region: ['广东省', '广州市', '番禺区'],
    titleEmpty: false,
    titleError: " ",
    typeEmpty: false,
    date1: "",
    date2: "",
    date3:"",
    date1Empty: false,
    date2Empty: false,
    date3Empty: false,
    peopleNum: "",
    peoNumError: "",
    phoneNum: "",
    judgePhone: false,
    phoneNumError: "",
    taskDetail: "",
    detailEmpty: false,
    imageList: [],
    imageUrl: "",
    timePopup1:false,
    timePopup2:false,
    startTime:"",
    endTime:"",
    timeEmpty:false,
    projectId:""

  },

 //生成二维码海报
 makeCode(data){
   this.setData({
     showCode:true
   })
  console.log(data)
    new QRCode('myQrcode',{
      text: "https://prod-9gpli53t5e32f92c-1311684025.tcloudbaseapp.com/aC84Bi4u6k.txt?sign=468db9b3e2d7c4807e8b93f33ccdbf14&t="+this.data.projectId,
      width: qrcode_w,
      height: qrcode_w,
      padding: 0, // 生成二维码四周自动留边宽度，不传入默认为0
      correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
      callback: (res) => {
        // 接下来就可以直接调用微信小程序的api保存到本地或者将这张二维码直接画在海报上面去，看需求
      }
    })
  },
    // 保存图片到相册
    savePhoto: function(index) {
      let that = this
      let imgs = that.data.imgs
      if (imgs[index].isDownLoad) {
        // 如果已经下载过 提示用户
        wx.showToast({
          title: '你已经下载过该图片',
          icon: 'none'
        })
        return
      } else {
        // 提示用户正在合成，否则用户可能有不当操作或者以为手机卡死
        wx.showLoading({
          title: '合成中......',
          mask: true
        })
  
        // 创建画布对象
        const ctx = wx.createCanvasContext("myCanvas", that)
        // 获取图片信息，要按照原图来绘制，否则图片会变形 
        wx.getImageInfo({
          src: "../../../images/recruitBackground.jpg",
          success: function(res) {
            // 根据 图片的大小 绘制底图 的大小
            console.log(" 绘制底图 的图片信息》》》", res)
            let imgW = res.width
            let imgH = res.height
            let imgPath = res.path
            that.setData({
              canvasHeight: imgH,
              canvasWidth: imgW
            })
            // 绘制底图 用原图的宽高比绘制
            ctx.drawImage(imgPath, 0, 0, imgW, imgH)
  
            wx.getImageInfo({
              src: that.data.codeImg, // 二维码图片的路径
              success: function(res) {
                console.log(" 绘制二维码》》》", res)
                // 绘制二维码
                ctx.drawImage(res.path, 50, imgH - 380, 300, 300)
                ctx.draw()
  
                wx.showLoading({
                  title: '正在保存',
                  mask: true
  
                })
  
                setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvasId: 'myCanvas',
                    success: function(res) {
                      console.log("合成的带有小程序码的图片success》》》", res)
                      let tempFilePath = res.tempFilePath
                      // 保存到相册
                      wx.saveImageToPhotosAlbum({
                        filePath: tempFilePath,
                        success(res) {
  
                          // 修改下载状态
                          imgs[index].isDownLoad = true
  
                          wx.hideLoading()
                          wx.showModal({
                            title: '温馨提示',
                            content: '图片保存成功，可在相册中查看',
                            showCancel: false,
                            success(res) {
                              wx.clear
                              if (res.confirm) {
                                that.setData({
                                  isShow: true
                                })
                              }
                            }
                          })
  
                          that.setData({
                            imgs: imgs,
                          })
                        },
  
                        fail(res) {
                          wx.hideLoading()
                          wx.showModal({
                            title: '温馨提示',
                            content: '图片保存失败，请重试',
                            showCancel: false
                          })
                        }
                      })
  
                      console.log("合成的带有小程序码的图片的信息》》》", res)
                    },
                    fail: function(res) {
                      console.log("生成的图拍呢 失败 fail fail fail ", res)
                      wx.hideLoading()
                      wx.showModal({
                        title: '温馨提示',
                        content: '小程序码图片合成失败，请重试',
                        showCancel: false
                      })
                    }
                  }, that)
                },1500)
              },
              fail(res) {
                wx.hideLoading()
                wx.showModal({
                  title: '温馨提示',
                  content: '二维码获取失败，请重试',
                  showCancel: false
                })
              }
            })
  
          },
          fail(res) {
            wx.hideLoading()
            wx.showModal({
              title: '温馨提示',
              content: '图片信息获取失败，请重试',
              showCancel: false
            })
          }
        })
      }
  
    },
  
  onLoad: async function (options) {
    let that = this
    let curYear = new Date().getFullYear()
    let curMonth = new Date().getMonth() + 1
    let curDay = new Date().getDate()
    const res = await wx.cloud.callContainer({
      "config": {
        "env": "prod-9gpli53t5e32f92c"
      },
      "path": "/projectDetail/ProjectDetail",
      "header": {
        "X-WX-SERVICE": "express-40vc"
      },
      "method": "POST",
      "data": {
        "action": "inc"
      }
    })
    console.log("1",res);
    this.setData({
      curYear:curYear,
      curMonth:curMonth,
      curDay:curDay
    })
  },

  showPopup() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false,
      timePopup1: false,
      timePopup2: false,
      showCode:false
    });
  },

  //任务标题
  taskTitle(e) {
    if (e.detail == "") {
      this.setData({
        titleError: "请输入任务名称",
      })
    } else {
      this.setData({
        taskTitle: e.detail,
        titleError: ""
      })
    }
    console.log(this.data.taskTitle)
  },

  //任务类型
  taskType(e) {
    this.setData({
      value1: e.detail,
      taskType: this.data.option1[e.detail].text,
      typeEmpty: false
    })
    // console.log(this.data.option1[e.detail].text)
    console.log(this.data.taskType)

  },

  //选择开始日期
  startDate: function (e) {
    let startDate = e.detail.value.replace(/-/g, "/")
    let startDateStamp = Date.parse(new Date(startDate));
    // console.log(x)
    // console.log(Number(e.detail.value.split('-')[2]))
    this.setData({
      endDateYear: Number(e.detail.value.split('-')[0]),
      endDateMonth: Number(e.detail.value.split('-')[1]),
      endDateDay: Number(e.detail.value.split('-')[2]),
      date1: e.detail.value,
      startDateStamp: startDateStamp,
      date1Empty: false,
    })
  },

  //选择结束日期
  endDate(e) {
    console.log(e.detail.value.slice(0,4))
    console.log(e.detail.value.slice(5,7))
    console.log(e.detail.value.slice(8,10))
    let endDateYear=e.detail.value.slice(0,4)
    let endDateMonth=e.detail.value.slice(5,7)-1
    let endDateDay=e.detail.value.slice(8,10)
    let endDateStamp = Date.parse(new Date(endDateYear,endDateMonth,endDateDay,23,59,59,999));
    console.log(endDateStamp)
    console.log(new Date(endDateStamp))
    this.setData({
      signEndDateYear: Number(e.detail.value.split('-')[0]),
      signEndDateMonth: Number(e.detail.value.split('-')[1]),
      signEndDateDay: Number(e.detail.value.split('-')[2]),
      date2: e.detail.value,
      endDateStamp: endDateStamp,
      date2Empty: false,
    })
  },

  //选择报名截止日期
  signEndDate(e) {
    let signEndDate = e.detail.value.replace(/-/g, "/")
    console.log("报名截止日期",signEndDate)
    console.log(e.detail.value.slice(0,4))
    console.log(e.detail.value.slice(5,7))
    console.log(e.detail.value.slice(8,10))
    let signEndYear=Number(e.detail.value.slice(0,4))
    let signEndMonth=Number(e.detail.value.slice(5,7))-1
    let signEndRi=Number(e.detail.value.slice(8,10))
    let signEndDateStamp = Date.parse(new Date(signEndYear,signEndMonth,signEndRi,'23','59','59','999'));
    console.log(signEndDateStamp)
    this.setData({
      date3: e.detail.value,
      signEndDateStamp: signEndDateStamp,
      date3Empty: false,
    })
  },

  //选择活动时段
  startTime(){
    this.setData({
      timePopup1:true,
    })
  },
  endTime(){
    this.setData({
      timePopup2:true,
    })
  },
  vlnTime1Can(){
    this.setData({
      timePopup1:false,
    })
  },
  vlnTime2Can(){
    this.setData({
      timePopup2:false,
    })
  },

  vlnTime1(e) {
    console.log(Number(e.detail.slice(0,2)))
    console.log(Number(e.detail.slice(4,6)))
    let minEndTimeHour=Number(e.detail.slice(0,2))
    let minEndTimeMinute=Number(e.detail.slice(4,6))
    this.setData({
      timePopup1:false,
      startTime:e.detail,
      endTimeValue:e.detail,
      minEndTimeHour:minEndTimeHour,
      minEndTimeMinute:minEndTimeMinute,
      timeEmpty:false,
    })
  },
  vlnTime2(e) {
    console.log(e.detail)
    this.setData({
      timePopup2:false,
      endTime:e.detail,
      timeEmpty:false,
    })
  },


  //选择地区
  chooseRegion: function (e) {
    this.setData({
      region: e.detail.value
    })
    console.log(e.detail.value)
    // console.log(this.data.region)

  },

  //输入所需人数
  peopleNum(e) {
    console.log(Number(e.detail))
    if (e.detail == "" || e.detail == 0) {
      this.setData({
        peoNumError: "请输入有效人数",
      })
    } else {
      this.setData({
        peopleNum: Number(e.detail),
        peoNumError: "",
      })
    }
  },

  //输入联系电话
  phoneNum(e) {
    console.log(e.detail)
    if (!phone.test(e.detail) || e.detail == "") {
      console.log("geshicuowu ")
      this.setData({
        phoneNumError: "请输入有效手机号",
      })
    } else {
      this.setData({
        phoneNumError: "",
        phoneNum: e.detail,
      })
    }
  },

  //获取该项目的ID
  getProjectID(){
    let projectId = getApp().getID(6, 2)
    this.setData({
      projectId:projectId,
      projectIDError:""
    })
  },

  //选择图片
  afterRead(e) {
    console.log(e)
    let temp = {
      url: e.detail.file.url,
      deletable: true,
    }
    let tempImage = []
    tempImage[0] = temp
    this.setData({
      imageList: tempImage
    })
  },
  deleteImage(e) {
    console.log(e)
    let tempImage = []
    this.setData({
      imageList: tempImage
    })
  },
  //输入具体描述
  taskDetail(e) {
    console.log(e.detail)
    this.setData({
      taskDetail: e.detail,
      detailEmpty: false
    })
  },

  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },


  //确认发布
  publish() {
    if (this.data.taskTitle == "") {
      this.setData({
        titleError: "请输入任务名称"
      })
      this.scrollTop()
    }

    if (this.data.taskType === "请选择任务类型") {
      this.setData({
        typeEmpty: true,
      })
      this.scrollTop()
    }

    if (this.data.date1 === "") {
      this.setData({
        date1Empty: true,
      })
      this.scrollTop()
    }

    if (this.data.date2 === "") {
      this.setData({
        date2Empty: true,
      })
      this.scrollTop()
    }

    if (this.data.date3 === "") {
      this.setData({
        date3Empty: true,
      })
      this.scrollTop()
    }

    if (this.data.startTime === "" || this.data.endTime === "") {
      this.setData({
        timeEmpty: true,
      })
      this.scrollTop()
    }

    if (this.data.peopleNum == 0 || this.data.peopleNum == "") {
      this.setData({
        peoNumError: "请输入有效人数",
      })
      this.scrollTop()
    }

    if (!phone.test(this.data.phoneNum) || this.data.phoneNum == "") {
      this.setData({
        phoneNumError: "请输入有效手机号",
      })
      this.scrollTop()
    }

    if (this.data.projectId=="") {
      this.setData({
        projectIDError: "请点击获取项目ID",
      })
      this.scrollTop()
    }

    if (this.data.taskDetail === "") {
      this.setData({
        detailEmpty: true,
      })
      this.scrollTop()
    }

    if (this.data.imageList.length == 0) {
      wx.showToast({
        title: '请选择一张图片',
        icon: 'none'
      })
    }
    if (this.data.taskTitle != "" && this.data.taskType != "请选择任务类型" && this.data.date1 != "" && this.data.date2 != "" && this.data.date3 != "" && this.data.startTime != "" &&this.data.endTime != "" &&this.data.peopleNum != 0&&this.data.projectId != "" && this.data.peopleNum != "" && phone.test(this.data.phoneNum) && this.data.phoneNum != "" && this.data.taskDetail != "" && this.data.imageList.length != 0) {
      console.log("团队发布人的openid",App.globalData.teamInfo._openid)
      console.log("团队的名字",App.globalData.teamInfo.teamInfo.teamName)
      console.log("团队的头像",App.globalData.teamInfo.teamInfo.teamImg)
      let teamOpenid=App.globalData.teamInfo._openid
      let teamNickname=App.globalData.teamInfo.teamInfo.teamName
      let teamAvatraurl=App.globalData.teamInfo.teamInfo.teamImg[0].url

      wx.cloud.uploadFile({
        cloudPath: this.data.taskTitle,
        filePath: this.data.imageList[0].url,
      }).then(res => {
        console.log("上传照片成功", res)
        this.setData({
          imageUrl: res.fileID
        })
        console.log(this.data.imageUrl)
        wx.cloud.callFunction({
            name: "pubTask",
            data: {
              taskTitle: this.data.taskTitle,
              taskType: this.data.taskType,
              startDateStamp: this.data.startDateStamp,
              endDateStamp: this.data.endDateStamp,
              signEndDateStamp: this.data.signEndDateStamp,
              startTime: this.data.startTime,
              endTime: this.data.endTime,
              region: this.data.region,
              peopleNum: this.data.peopleNum,
              phoneNum: this.data.phoneNum,
              taskDetail: this.data.taskDetail,
              imageUrl: this.data.imageUrl,
              //发布时候的时间戳
              pubTimeStamp: Date.parse(new Date()),
              pubYear: new Date().getFullYear(),
              pubMonth: new Date().getMonth() + 1,
              pubDate: new Date().getDate(),
              projectId:this.data.projectId,
              teamOpenid:teamOpenid,
              teamNickname:teamNickname,
              teamAvatraurl:teamAvatraurl,
            }
          })
          .then(res => {
            console.log("调用成功", res)
            wx.navigateBack({
              delta: 1
            })
          })
          .catch(err => {
            console.log("调用失败", err)
          })
      })
    }
  }
})